﻿using System;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace XClient
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        #region · Protected Methods ·

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnDomainUnhandledException);

            ShellApplication.Instance.Run();
        }

        #endregion

        #region · Unhandled Exception ·

        private void OnDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;

            if (ex != null)
            {
#warning Log exception && Show the exception details
                MessageBox.Show(ex.ToString());
            }
            else
            {
#warning Log error && Show the error details
                MessageBox.Show("An Exception has occured, unable to get details");
            }
        }

        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            Exception ex = e.Exception;

            if (ex != null)
            {
#warning Log exception && Show the exception details
                MessageBox.Show(ex.ToString());
            }
            else
            {
#warning Log error && Show the error details
                MessageBox.Show("An Exception has occured, unable to get details");
            }

            e.Handled = true;
        }

        private string BuildExceptionString(Exception exception)
        {
            StringBuilder messageBuilder = new StringBuilder();

            messageBuilder.AppendFormat("{0}{1}{2}", exception.Message, Environment.NewLine, exception.StackTrace);

            while (exception.InnerException != null)
            {
                messageBuilder.Append(BuildInnerExceptionString(exception.InnerException));

                exception = exception.InnerException;
            }

            return messageBuilder.ToString();
        }

        private string BuildInnerExceptionString(Exception innerException)
        {
            StringBuilder messageBuilder = new StringBuilder();

            messageBuilder.AppendFormat("{0}{1}", Environment.NewLine, " InnerException ");
            messageBuilder.AppendFormat("{0}{1}{2}{3}", Environment.NewLine, innerException.Message, Environment.NewLine, innerException.StackTrace);

            return messageBuilder.ToString();
        }

        #endregion
    }
}
